const path = require('path')
const webpack = require('webpack')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const outputPath = '../dist'
const packageJson = require('../package.json')
const CustomPlugin = require('./CustomPlugin')
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin') // 需要用到monaco-editor的话需要这个插件

const top = `/*!
* 亿通平台架构部 - TITAN研发组
* 未经许可，不得使用！
* (c) 2001-${new Date().getFullYear()} easipass.com
*/
window.chunkLoader.initChunk(function (chunkResource, EPENV) {`
const bottom = `;return epChunkVm}, document.currentScript && document.currentScript.id || '')`
exports.getConfig = (pageName, APP_ID, entry, plugins) => {
  let configRes = {
    // entry: {
    //   hello: './chunk/views/hello/helloWorld/index.js'
    // },
    entry,
    output: {
      // clean: true,
      path: path.join(__dirname, outputPath, './chunk', APP_ID, pageName),
      filename: `[name].js`,
      // chunkFilename: '[id].js',
      library: 'epChunkVm',
      libraryTarget: 'var',
      umdNamedDefine: true
    },

    externals: [
      function (context, request, callback) {
        // 这个和预编译的那些没啥关系
        // 这边新增的话，对应的主程序 @easipass/chunk-render/core/chunkLoader.js 也要更新 注入相应的
        var externalArr = ['vue', 'vue-router', 'vuex', 'axios', 'echarts', 'blueimp-md5', 'qs', 'ep-ui', '@easipass/epin-render-plus']

        if (request === '@/store' || request === 'src/store') {
          return callback(null, 'var chunkResource.VueStore')
        } else if (request === '@/router' || request === 'src/router') {
          return callback(null, 'var chunkResource.VueRouter')
        } else if (request === '@/settings' || request === 'src/settings') {
          return callback(null, 'var chunkResource.appSetting')
        } else if (externalArr.indexOf(request) > -1) {
          return callback(null, `var chunkResource.lib['${request}']`)
        }
        callback()
      }
    ],
    optimization: {
      splitChunks: false
    },

    resolve: {
      extensions: ['.js', '.vue', '.json'],
      alias: {
        src: path.join(__dirname, '../src'),
        '@': path.join(__dirname, '../src'),
        chunk: path.join(__dirname, '../chunk')
      },
      modules: ['node_modules']
    },

    module: {
      rules: [
        {
          test: /\.(jsx?|babel|es6)$/,
          include: process.cwd(),
          exclude: /node_modules/,
          loader: 'babel-loader',
          options: {
            plugins: [
              // 动态import() 引起的分包问题，如果后面出问题，那就删掉这边，代码里别用动态import就行
              // 动态引入图片有问题，开发中动态导入后console出来是个模块，打包后 console出来时base64
              // 现在已经支持分块加载所以这边也不需要了
              // 'dynamic-import-webpack',
              // 'remove-webpack'
            ]
          }
        },
        {
          test: /\.js$/,
          include: /node_modules[\\\/]@easipass[\\\/].*/,
          exclude: /node_modules[\\\/]@easipass[\\\/]epin-render-plus[\\\/]dist/,
          // include: /node_modules[\\\/]@easipass[\\\/]utils|node_modules[\\\/]@easipass[\\\/]basic|node_modules[\\\/]@easipass[\\\/]epin|node_modules[\\\/]@easipass[\\\/]area-data|node_modules[\\\/]@easipass[\\\/]chunk-render/,
          loader: 'babel-loader'
        },
        {
          test: /\.vue$/,
          loader: 'vue-loader',
          options: {
            preserveWhitespace: false
          }
        },
        {
          test: /\.css$/,
          use: ['vue-style-loader', 'css-loader']
        },
        {
          test: /\.less$/,
          use: ['vue-style-loader', 'css-loader', 'less-loader']
        },
        {
          test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
          loader: 'url-loader',
          options: {
            limit: 10000000, // 为了方便性，10m 以内会打包进去，但是还是建议用小点的资源奥
            name: '[name].[hash:7].[ext]'
            // name: path.join(APP_ID, `[name].[hash:7].[ext]`)
            // name: path.join(__dirname, outputPath + "/chunk/[name].[hash:7].[ext]")
          }
        },
        {
          test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
          loader: 'url-loader',
          options: {
            limit: 10000000, // 为了方便性，10m 以内会打包进去，但是还是建议用小点的资源奥
            name: '[name].[hash:7].[ext]'
          }
        }
      ]
    },
    plugins: [
      new CleanWebpackPlugin(), //清理文件夹
      new webpack.DefinePlugin({
        SCRIPT_TYPE: JSON.stringify('build') // serve为开发模式， build为打包模式
      }),
      new VueLoaderPlugin(),
      new webpack.optimize.LimitChunkCountPlugin({
        maxChunks: 1
      }),
      // 定制插件
      new CustomPlugin({
        top,
        bottom
      })
    ]
  }
  if (plugins && plugins.indexOf('monaco') > -1) {
    configRes.plugins.push(
      new MonacoWebpackPlugin({
        features: ['!gotoSymbol'],
        languages: ['javascript', 'css', 'html', 'typescript', 'json']
      })
    )
  }
  return configRes
}
